#!/usr/bin/env python3
"""
ADAM模型演示程序

该程序演示如何使用基于Excel参数的ADAM（Advanced Dissolution, Absorption, and Metabolism）模型
进行详细的药物吸收分析。

作者：BlackCat@CPPO
版本：1.0.0
"""

import os
import sys
import numpy as np
import matplotlib.pyplot as plt

# 添加项目根目录到路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

from src.absorption.absorption_module import AbsorptionModel
from src.absorption.adam_model import ADAMModel
from src.visualization.plot_generator import PlotGenerator

def demo_adam_model():
    """演示ADAM模型功能"""
    
    print("=== ADAM Model Demo ===")
    
    # Sample drug parameters
    drug_params = {
        'dose': 100,  # mg
        'solubility': 0.8,  # mg/mL
        'permeability': 2e-4,  # cm/s
        'molecular_weight': 325.4,  # g/mol
        'pKa': 7.8,
        'logP': 2.5,
        'particle_size': 50,  # μm
        'density': 1.2,  # g/cm³
        'use_adam': True
    }
    
    # 创建吸收模型（启用ADAM）
    absorption_model = AbsorptionModel(drug_params)
    
    # 创建ADAM模型直接使用
    adam_model = ADAMModel(drug_params)
    
    # 时间设置
    time_points = np.linspace(0, 24, 100)
    
    # 计算BCS分类
    print("\n1. BCS分类分析")
    bcs_result = absorption_model.calculate_bcs_classification(
        drug_params['solubility'],
        drug_params['permeability'],
        drug_params['dose']
    )
    print(f"BCS分类: {bcs_result['class']}")
    print(f"高溶解性: {bcs_result['high_solubility']}")
    print(f"高渗透性: {bcs_result['high_permeability']}")
    print(f"剂量溶解度比: {bcs_result['dose_solubility_ratio']:.2f}")
    
    # 计算ADAM吸收
    print("\n2. ADAM模型吸收分析")
    adam_result = adam_model.calculate_adam_absorption(time_points)
    print(f"生物利用度: {adam_result['bioavailability']:.2f}")
    print(f"最终吸收分数: {adam_result['fraction_absorbed'][-1]:.2f}")
    
    # 区域吸收分析
    print("\n3. 区域吸收分析")
    regional_total = {}
    for region, amounts in adam_result['regional_absorbed'].items():
        total_absorbed = np.sum(amounts) * (time_points[1] - time_points[0])
        regional_total[region] = total_absorbed
        print(f"{region}: {total_absorbed:.2f} mg")
    
    # 使用吸收模型计算
    print("\n4. 集成吸收模型")
    absorption_result = absorption_model.calculate_absorption({}, time_points)
    print(f"总生物利用度: {absorption_result['bioavailability']:.2f}")
    
    # 创建可视化
    visualizer = PlotGenerator()
    
    # 绘制区域吸收曲线
    plt.figure(figsize=(15, 10))
    
    # Subplot 1: Regional drug amounts
    plt.subplot(2, 2, 1)
    for region, amounts in adam_result['regional_amounts'].items():
        plt.plot(time_points, amounts, label=region)
    plt.xlabel('Time (hours)')
    plt.ylabel('Drug amount (mg)')
    plt.title('Regional drug amounts over time')
    plt.legend()
    plt.grid(True)
    
    # Subplot 2: Cumulative absorption
    plt.subplot(2, 2, 2)
    plt.plot(time_points, adam_result['cumulative_absorption'], 'b-', linewidth=2)
    plt.xlabel('Time (hours)')
    plt.ylabel('Cumulative absorption (mg)')
    plt.title('Cumulative drug absorption')
    plt.grid(True)
    
    # Subplot 3: Regional absorption rates
    plt.subplot(2, 2, 3)
    for region, rates in adam_result['regional_absorbed'].items():
        plt.plot(time_points, rates, label=region)
    plt.xlabel('Time (hours)')
    plt.ylabel('Absorption rate (mg/h)')
    plt.title('Regional absorption rates')
    plt.legend()
    plt.grid(True)
    
    # Subplot 4: Regional contribution pie chart
    plt.subplot(2, 2, 4)
    labels = list(regional_total.keys())
    sizes = list(regional_total.values())
    plt.pie(sizes, labels=labels, autopct='%1.1f%%')
    plt.title('Regional absorption contribution')
    
    plt.tight_layout()
    plt.show()
    
    return {
        'bcs_classification': bcs_result,
        'adam_absorption': adam_result,
        'regional_analysis': regional_total
    }

def demo_bcs_integration():
    """演示BCS集成使用样本参数"""
    
    print("\n=== BCS集成演示 ===")
    
    # 创建吸收模型
    absorption_model = AbsorptionModel({})
    
    # 使用样本参数演示
    sample_params = {
        'dose': 100,
        'solubility': 14.0,
        'permeability': 1.2e-05,
        'pKa': 9.38,
        'logP': 0.46
    }
    
    # 计算BCS集成
    bcs_integration = absorption_model.calculate_bcs_classification(
        sample_params['solubility'],
        sample_params['permeability'], 
        sample_params['dose']
    )
    print(f"BCS集成完成: {bcs_integration['class']}")
    print(f"分类详情: {bcs_integration}")
    
    return bcs_integration

def demo_food_effect():
    """演示食物效应"""
    
    print("\n=== 食物效应演示 ===")
    
    # 空腹状态参数
    fasted_params = {
        'dose': 100,
        'solubility': 1.0,
        'permeability': 1e-4,
        'use_adam': True
    }
    
    # 餐后状态参数
    fed_params = {
        'dose': 100,
        'solubility': 1.5,  # 食物可能增加溶解度
        'permeability': 0.8e-4,  # 食物可能降低渗透性
        'use_adam': True
    }
    
    time_points = np.linspace(0, 24, 100)
    
    # 创建模型实例
    fasted_model = AbsorptionModel(fasted_params)
    fed_model = AbsorptionModel(fed_params)
    
    # 计算吸收
    fasted_result = fasted_model.calculate_absorption({}, time_points)
    fed_result = fed_model.calculate_absorption({}, time_points)
    
    # 计算食物效应
    fasted_auc = np.trapezoid(fasted_result['rate'], time_points)
    fed_auc = np.trapezoid(fed_result['rate'], time_points)
    food_effect_ratio = fed_auc / fasted_auc
    
    print(f"空腹AUC: {fasted_auc:.2f} mg·h/L")
    print(f"餐后AUC: {fed_auc:.2f} mg·h/L")
    print(f"食物效应比: {food_effect_ratio:.2f}")
    
    if food_effect_ratio > 1.2:
        print("食物增加吸收")
    elif food_effect_ratio < 0.8:
        print("食物减少吸收")
    else:
        print("食物无显著影响")

if __name__ == "__main__":
    # 运行演示
    demo_adam_model()
    demo_bcs_integration()
    demo_food_effect()
    
    print("\n=== ADAM模型演示完成 ===")